//
//  JKCommentViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/8.
//  Copyright © 2018年 安永博. All rights reserved.
//  评论

import UIKit
import JKAlertX

class JKCommentViewController: JKBaseViewController {

    // MARK: - 公共属性
    
    /** 文章的ID */
    var storyID: String?
    
    /** 扩展数据模型 */
    var extraModel: JKNewsDetailExtraModel?
    
    
    // MARK: - 私有属性
    
    /** 记录短评论是否展开 */
    private var _shortCmtUnfolded = false
    
    private let bottomViewH: CGFloat = 40
    
    private let commentCellID = "JKCommentCell"
    private let commentEmptyCellID = "JKCommentEmptyCell"
    
    /** 长评论模型数据 */
    private var longCmts = [JKCommentModel]()
    
    /** 短评论模型数据 */
    private var shortCmts = [JKCommentModel]()
    
    /** 所有评论 存储的是长评论集合 + 短评论集合 */
    private var cmts: [[JKCommentModel]] {
        
        return [longCmts, shortCmts]
    }
    
    /** 底部视图 */
    private lazy var bottomView: UIView = {
        
        let bottomView = UIView()
        
        bottomView.backgroundColor = JKSameRGBColor(36)
        bottomView.frame = CGRect(x: 0,
                                  y: JKScreenH - bottomViewH - JKCurrentHomeIndicatorHeight,
                                  width: JKScreenW,
                                  height: bottomViewH + JKCurrentHomeIndicatorHeight)
        contentView.addSubview(bottomView)
        
        // 返回按钮
        let backBtn = UIButton(type: UIButtonType.custom)
        backBtn.setImage(UIImage(named: "Back_White"), for: UIControlState.normal)
        backBtn.setImage(UIImage(named: "Back"), for: UIControlState.highlighted)
        backBtn.frame = CGRect(x: 5, y: 0, width: bottomViewH, height: bottomViewH)
        backBtn.addTarget(self, action: #selector(navBackButtonClick), for: UIControlEvents.touchUpInside)
        bottomView.addSubview(backBtn)
        
        // 分割线
        let sepLineView = UIView()
        sepLineView.backgroundColor = UIColor.white.withAlphaComponent(0.2)
        sepLineView.frame = CGRect(x: 35, y: 0, width: 1, height: bottomViewH)
        bottomView.addSubview(sepLineView)
        
        // 写点评
        let writeCmtBtn = UIButton(type: UIButtonType.custom)
        
        writeCmtBtn.frame = CGRect(x: 36, y: 0, width: JKScreenW - 36, height: bottomViewH)
        writeCmtBtn.setImage(UIImage(named: "Comment_Icon_Compose"), for: UIControlState.normal)
        writeCmtBtn.setTitle("写点评", for: UIControlState.normal)
        writeCmtBtn.setTitleColor(JKSameRGBColor(217), for: UIControlState.normal)
        writeCmtBtn.setTitleColor(UIColor.darkGray, for: UIControlState.highlighted)
        writeCmtBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        writeCmtBtn.centerX = JKScreenW * 0.5
        writeCmtBtn.addTarget(self, action: #selector(writeCmtBtnClick), for: UIControlEvents.touchUpInside)
        bottomView.addSubview(writeCmtBtn)
        
        return bottomView
    }()
    
    /** 遮盖短评视图 */
    private var coverView: UIView?
    
    /** selectCell */
    private var selectCell: JKCommentCell?
    
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        JKProgressHUD.dismiss()
        
        UIMenuController.shared.setMenuVisible(false, animated: true)
        self.selectCell?.isSelected = false
    }
    
    // MARK: - 初始化
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navBackButton.isHidden = true
        
        navTitle = (extraModel != nil) ? extraModel!.comments! + "条评论" : "评论"
    }
    
    override func setupTableView() {
        
        tableViewPlain.backgroundColor = UIColor.clear
        tableViewPlain.contentInset = UIEdgeInsetsMake(JKNavBarHeight, 0, bottomViewH + JKCurrentHomeIndicatorHeight, 0)
        
        if #available(iOS 11.0, *) {
            
            tableViewPlain.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, bottomViewH, 0)
            
        } else {
            
            tableViewPlain.scrollIndicatorInsets = tableViewPlain.contentInset
        }
        
        tableViewPlain.estimatedRowHeight = 100
        tableViewPlain.estimatedSectionHeaderHeight = 40
        
        tableViewPlain.register(UINib(nibName: commentCellID, bundle: nil), forCellReuseIdentifier: commentCellID)
        tableViewPlain.register(UINib(nibName: commentEmptyCellID, bundle: nil), forCellReuseIdentifier: commentEmptyCellID)
        
        let _ = bottomView
    }
    
    
    // MARK: - 加载数据
    
    override func loadNewData() {
        
        JKProgressHUD.showWithLoadingIsAllowUserAction(isAllowUserAction: true)
        
        if storyID == nil { return }
        
        JKCommentListGetDataModel.getAllLongCommentsWithNewsID(newsID: storyID!) { (models) in
            
            if models == nil {
                
                JKProgressHUD.dismiss()
                
                return
            }
            
            self.longCmts = models!
            
            JKCommentListGetDataModel.getAllShortCommentsWithNewsID(newsID: self.storyID!, finishedBlock: { (shortModels) in
                
                if shortModels == nil {
                    
                    JKProgressHUD.dismiss()
                    
                    return
                }
                
                self.shortCmts = shortModels!
                
                self.navTitle = "\(self.longCmts.count + self.shortCmts.count)条评论"
                
                JKProgressHUD.dismiss()
                
                self.tableViewPlain.reloadData()
            })
        }
    }
    
    // MARK: - 点击事件
    
    /** 写点评 */
    @objc private func writeCmtBtnClick() {
        
        
        let vc = JKCommentComposeViewController()
        let nav = JKMainNavigationController(rootViewController: vc)
        
        vc.navTitle = "评论"
        
        present(nav, animated: true, completion: nil)
        
        selectCell?.isSelected = false
    }
    
    // MARK: - 短评论是否展开
    
    /** 短评论是否展开 */
    @objc private func unfoldShortCmt(button: UIButton) {
        
        selectCell?.isSelected = false
        
        _shortCmtUnfolded = !_shortCmtUnfolded
        
        // 长评论最后一个cell的索引
        let lastLongCmtIndexPath = (self.longCmts.count > 0) ?
            IndexPath(row: self.longCmts.count - 1, section: 0) :
            IndexPath(row: 0, section: 0)
        
        let lastLongCmtRect = tableViewPlain.rectForRow(at: lastLongCmtIndexPath)
        
        let firstLongCmtRect = tableViewPlain.rectForRow(at: IndexPath(row: 0, section: 0))
        let indexSet = IndexSet.init(integer: 1)//.Index//[NSIndexSet indexSetWithIndex:1];
        
        // 收起
        if (!_shortCmtUnfolded) {
            
            tableViewPlain.reloadSections(indexSet, with: UITableViewRowAnimation.automatic)
            
            if (lastLongCmtRect.maxY - firstLongCmtRect.origin.y <= self.tableViewPlain.height - 40) {
                
                return;
            };
            
            UIView.animate(withDuration: 0.5, animations: {
                
                self.tableViewPlain.scrollToRow(at: lastLongCmtIndexPath, at: UITableViewScrollPosition.top, animated: true)
            })
            
            return;
        }
        
        // 展开
        tableViewPlain.reloadSections(indexSet, with: UITableViewRowAnimation.automatic)
        
        // 第二组第一个cell的frame
        let firstShortCmtRect = tableViewPlain.rectForRow(at: IndexPath(row: 0, section: 1))
        
        // 第二组最后cell的frame
        let lastShortCmtRect = tableViewPlain.rectForRow(at: IndexPath(row: shortCmts.count - 1, section: 1))
        
        // 短评的总高度
        let shortCmtHeight = lastShortCmtRect.maxY - firstShortCmtRect.origin.y;
        
        // 短评论的总高度小于中间显示区域的高度
        if (shortCmtHeight <= self.tableViewPlain.height - 40) {
            
            UIView.animate(withDuration: 0.5, animations: {
                
                self.tableViewPlain.scrollToRow(at: IndexPath(row: self.shortCmts.count - 1, section: 1), at: UITableViewScrollPosition.bottom, animated: true)
            })
            
            return;
        }
        
        UIView.animate(withDuration: 0.5, animations: {
            
            self.tableViewPlain.scrollToRow(at: IndexPath(row: 0, section: 1), at: UITableViewScrollPosition.top, animated: true)
        })
    }
    
    // MARK: - UIMenuController点击处理
    
    // 赞同
    @objc private func zan(menu: UIMenuController) {
        
        // 获取选中的行
        guard let indexPath = tableViewPlain.indexPathForSelectedRow else { return }

        // 获取选中行对应的模型，取得评论的内容
        let comment = self.cmts[indexPath.section][indexPath.row]
        comment.isLiked = !comment.isLiked
        
        let likeCount = Int(comment.likes ?? "0")
        
        comment.likes = (comment.isLiked) ? "\((likeCount ?? 0) + 1)" : "\((likeCount ?? 1) - 1)"
        
        selectCell?.isSelected = false

        // 取出选中的cell
        selectCell?.zanClick()
    }
    
    // 回复
    @objc private func respond(menu: UIMenuController) {
        
        // 获取选中的行
        guard let indexPath = tableViewPlain.indexPathForSelectedRow else { return }
        
        // 获取选中行对应的模型，取得评论的内容
        let comment = self.cmts[indexPath.section][indexPath.row]
        
        let vc = JKCommentComposeViewController()
        let nav = JKMainNavigationController(rootViewController: vc)
        
        vc.navTitle = "回复" + (comment.author ?? "0.0")
        
        present(nav, animated: true, completion: nil)

        selectCell?.isSelected = false
    }
    
    // 复制
    @objc private func copyText(menu: UIMenuController) {
        
        // 获取选中的行
        guard let indexPath = tableViewPlain.indexPathForSelectedRow else { return }
        
        selectCell?.isSelected = false
        
        // 获取选中行对应的模型，取得评论的内容
        let comment = self.cmts[indexPath.section][indexPath.row]

        let board = UIPasteboard.general
        board.string = comment.content
        JKProgressHUD.showSuccess(withStatus: "复制成功！")
    }
    
    // 举报
    @objc private func report(menu: UIMenuController) {
        
        selectCell?.isSelected = false
        
        let _ = JKAlertView(title: nil, message: "太好了 让我们一起净化评论区", style: JKAlertStylePlain).addAction(JKAlertAction(title: "取消", style: JKAlertActionStyleCancel, handler: { (action) in
            
            
        }))?.addAction(JKAlertAction(title: "确认举报", style: JKAlertActionStyleDefault, handler: { (action) in
            
            
            
        }))?.show()
    }
    
    deinit {
        
        JKCommentListGetDataModel.clearData()
    }
}

// MARK: - taleview数据源

extension JKCommentViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return cmts.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if ((section == 0) && (self.longCmts.count == 0)) {
            
            return 1
            
        }else if (section == 0){
            
            return self.cmts[section].count
            
        }else{
            
            return _shortCmtUnfolded ? self.cmts[section].count : 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if ((indexPath.section == 0) && (self.longCmts.count == 0)) { // 没有长评论
            
            return JKScreenH - (JKStatusBarHeight + JKBarHeight) - bottomViewH - 40 - JKCurrentHomeIndicatorHeight
        }
        
        let model = cmts[indexPath.section][indexPath.row]
        
        let _ = model.cellHeight
        
        return (model.cmtRefUnfolded) ? model.cellHeight : model.cellFoldHeight
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if ((indexPath.section == 0) && (self.longCmts.count == 0)) { // 没有长评论
            
            var cell = tableView.dequeueReusableCell(withIdentifier: commentEmptyCellID) as? JKCommentEmptyCell
            
            if cell == nil {
                
                cell = JKCommentEmptyCell(style: UITableViewCellStyle.default, reuseIdentifier: commentEmptyCellID)
            }
            
            return cell!
        }
        
        let cmtModel = self.cmts[indexPath.section][indexPath.row]
        
        var cell = tableView.dequeueReusableCell(withIdentifier: commentCellID) as? JKCommentCell//[tableView dequeueReusableCellWithIdentifier:commentCellID]
        
        if cell == nil {
            
            cell = JKCommentCell(style: UITableViewCellStyle.default, reuseIdentifier: commentCellID)
        }
        
        cell!.separatorLineView.isHidden = (indexPath.row == 0)
        
        if (cell!.delegate == nil) {
            
            cell!.delegate = self
        }
        
        cell!.cmtModel = cmtModel
        
        return cell!
    }
}


// MARK: - taleview代理

extension JKCommentViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if (indexPath.section == 0 && self.longCmts.count < 1) { return }
        
        // 取出选中的cell
        let cell = tableView.cellForRow(at: indexPath) as! JKCommentCell//(CommentCell *)[tableView cellForRowAtIndexPath:indexPath]
        
        selectCell = cell
        
        let comment = cmts[indexPath.section][indexPath.row]
        
        // UIMenuController
        if (!comment.isMenuAdded) {
            
            comment.menu = UIMenuController.shared
            comment.isMenuAdded = true
        }
        
        cell.isSelected = !UIMenuController.shared.isMenuVisible
        
        // 如果menu已经显示了，再次点击要隐藏
        if (comment.menu!.isMenuVisible) {
            
            // 隐藏menu
            UIMenuController.shared.setMenuVisible(false, animated: true)
            
            return
        }
        
        // 让cell成为第一响应者。只要卸任第一响应者，menu就会消失
        cell.becomeFirstResponder()
        
        // 自定义item
        let zan = UIMenuItem(title: (comment.isLiked) ? "取消赞同" : "赞同", action: #selector(zan(menu:)))
        let report = UIMenuItem(title: "举报", action: #selector(report(menu:)))
        let copy = UIMenuItem(title: "复制", action: #selector(copyText(menu:)))
        let respond = UIMenuItem(title: "回复", action: #selector(respond(menu:)))
        
        comment.menu!.menuItems = [zan, report, copy, respond]
        
        // 让menu显示在cell中间
        let rect = CGRectMake(0, cell.height * 0.5, cell.width, cell.height * 0.5)
        
        comment.menu!.setTargetRect(rect, in: cell)
        comment.menu!.setMenuVisible(true, animated: true)
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if (section == 0) {
            
            return (self.longCmts.count == 0) ? 0 : 40
        }
        
        return (self.shortCmts.count == 0) ? 0 : 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let sectionHeaderView  = JKCommentSectionHeaderView.headerViewWithTableView(tableView: tableView)
        
        sectionHeaderView.frame = CGRectMake(0, 0, JKScreenW, 40)
        
        sectionHeaderView.unfoldButtonAddTarget(target: self, action: #selector(unfoldShortCmt(button:)))
        
        if ((section == 0) && (self.longCmts.count == 0)) { // 没有长评论，隐藏展开按钮
            
            sectionHeaderView.unfoldButtonHidden = true
            
            return nil
            
        }else if (section == 0) { // 长评论，隐藏展开按钮
            
            sectionHeaderView.unfoldButtonHidden = true
            sectionHeaderView.isHidden = false
            sectionHeaderView.cmtCountText = String(format: "%d 条长评", (self.cmts[section].count))
            
        }else{ // 短评论
            
            // 刷新表格后恢复按钮的选中状态
            sectionHeaderView.resetUnfoldButtonSelected(shortCmtUnfolded: _shortCmtUnfolded)
            
            sectionHeaderView.unfoldButtonHidden = (self.shortCmts.count == 0)
            sectionHeaderView.isHidden = (self.shortCmts.count == 0)
            sectionHeaderView.cmtCountText = String(format: "%d 条短评", (self.cmts[section].count))
        }
        
        return sectionHeaderView
    }
}

// MARK: - scrollView代理

extension JKCommentViewController {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        UIMenuController.shared.setMenuVisible(false, animated: true)
        selectCell?.isSelected = false
    }
}


// MARK: - 展开和收起引用评论
extension JKCommentViewController: JKCommentCellProtocol{
    
    func commentCellDidClickUnfoldButton(cell: JKCommentCell, button: UIButton) {
        
        self.selectCell?.isSelected = false
        cell.isSelected = false
        
        // 隐藏menu
        UIMenuController.shared.setMenuVisible(false, animated: true)
        
        guard let indexPath = tableViewPlain.indexPath(for: cell) else { return }
        
        let model = self.cmts[indexPath.section][indexPath.row]
        
        model.cmtRefUnfolded = button.isSelected
        
        tableViewPlain.beginUpdates()
        
        cell.cmtModel = model
        
        tableViewPlain.endUpdates()
        /*
        if #available(iOS 11.0, *) {
            
            tableViewPlain.performBatchUpdates({
                
                tableViewPlain.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
                
            }) { (_) in
                
            }
            
        } else {
            
            tableViewPlain.beginUpdates()
            
            tableViewPlain.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
            
            tableViewPlain.endUpdates()
        }
        */
    }
}

extension JKCommentViewController {
    
    override func updateSkin() {
        
        if vcSkinModel == currentSkinModel {
            return
        }
        
        super.updateSkin()
        
        selectCell?.isSelected = false
        UIMenuController.shared.setMenuVisible(false, animated: true)
    }
}
